package com.maruti.otterapi.populartrackbacks;

import com.maruti.otterapi.ListParameters;
import com.maruti.otterapi.Otter4JavaException;
import com.maruti.otterapi.TopsyConfig;
import com.maruti.otterapi.TopsyConstants;
import com.maruti.otterapi.TopsyInvoker;

public class Populartrackbacks {

	private TopsyConfig topsyConfig;

	public TopsyConfig getTopsyConfig() {
		return topsyConfig;
	}

	public void setTopsyConfig(TopsyConfig topsyConfig) {
		this.topsyConfig = topsyConfig;
	}

	public PopulartrackbacksResponse populartrackbacks(String url)
			throws Otter4JavaException {
		return fetchAll(url);
	}

	public PopulartrackbacksResponse populartrackbacks(String url, ListParameters listParams)
			throws Otter4JavaException {
		return fetch(url, listParams);
	}

	private PopulartrackbacksResponse fetchAll(String url) throws Otter4JavaException {

		int page = 1;
		ListParameters listParameters = new ListParameters();
		listParameters.setPage("" + page);
		listParameters.setPerpage("100");

		PopulartrackbacksResponse response = fetch(url, listParameters);
		int total = Integer.parseInt(response.getResponse().getTotal());
		System.out.println(total);
		int fetchedRecs = response.getResponse().getList().size();
		PopulartrackbacksResponse response1 = null;
		//String lastOffset = response.getResponse().getLast_offset();
		page++;
		while (total > fetchedRecs && page <= 10) {
			listParameters.setPage("" + page);
			// listParameters.setOffset(lastOffset);
			response1 = fetch(url, listParameters);
			response.getResponse().getList().addAll(
					response1.getResponse().getList());
			fetchedRecs += response1.getResponse().getList().size();
			System.out.println(response1.getResponse().getList().size());
			//lastOffset = response1.getResponse().getLast_offset();
			page++;
		}

		return response;
	}

	private PopulartrackbacksResponse fetch(String url,
			ListParameters listParams) throws Otter4JavaException {
		TopsyInvoker invoker = new TopsyInvoker();
		invoker.setTopsyConfig(topsyConfig);

		String query = url + listParams.toQuery();

		PopulartrackbacksResponse data = (PopulartrackbacksResponse) invoker
				.fetchData(TopsyConstants.populartrackbacksURL + query,
						"populartrackbacks");

		return data;
	}

}
